#!/bin/sh
# NSO Classic macOS App Launcher
# Invariant C1: Redirect CWD to ~/Library/Application Support/NSO Classic to persist RMS & config

set -eu

# Resolve absolute path to Resources directory inside the .app bundle
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
RESOURCES_DIR="$(cd "$SCRIPT_DIR/../Resources" && pwd)"

USER_DATA_DIR="$HOME/Library/Application Support/NSO Classic"
mkdir -p "$USER_DATA_DIR"

# Seed default game.conf if not already present
if [ ! -f "$USER_DATA_DIR/config/NSO Classic/game.conf" ]; then
    mkdir -p "$USER_DATA_DIR/config/NSO Classic"
    if [ -f "$RESOURCES_DIR/config/NSO Classic/game.conf" ]; then
        cp "$RESOURCES_DIR/config/NSO Classic/game.conf" "$USER_DATA_DIR/config/NSO Classic/game.conf"
    fi
fi

# Switch working directory to user data dir before starting JVM
cd "$USER_DATA_DIR"

# Resolve embedded Java executable
JAVA_EXEC="$RESOURCES_DIR/jre/bin/java"
if [ ! -x "$JAVA_EXEC" ]; then
    # Fallback to system java if embedded JRE is not executable
    JAVA_EXEC="$(command -v java || true)"
fi

if [ -z "$JAVA_EXEC" ] || [ ! -x "$JAVA_EXEC" ]; then
    osascript -e 'display dialog "Không tìm thấy Java Runtime để khởi chạy NSO Classic. Vui lòng thử cài lại ứng dụng." with title "NSO Classic Error" buttons {"OK"} default button "OK" with icon stop'
    exit 1
fi

EMULATOR_JAR="$RESOURCES_DIR/freej2me.jar"
GAME_JAR="$RESOURCES_DIR/game.jar"

exec "$JAVA_EXEC" \
    -Dfile.encoding=ISO_8859_1 \
    -Xdock:name="NSO Classic" \
    -jar "$EMULATOR_JAR" \
    "$GAME_JAR" 0 640 360 1
